#include <string.h>
#include "cgi_helper.h"
#include "z_memory.h"

http_request_t *http_request_new() {
    http_request_t *ptr = z_calloc(1, sizeof(http_request_t));
    ptr->request_method = HTTP_METHOD_GET;
    return ptr;
}

void http_request_free(http_request_t *ptr) {
    if (ptr) {
        if (ptr->json) {
            cJSON_Delete(ptr->json);
        }
        z_free(ptr);
    }
}

int http_request_from_args(http_request_t *request, int argc, char *argv[]) {
    for (int i = 1; i < argc; ++i) {
        if (0 == strcmp("--method", argv[i])) {
            request->request_method = argv[++i];
        } else if (0 == strcmp("--query", argv[i])) {
            request->query_string = argv[++i];
        }
    }
}


#define BURSIZE 2048

int hex2dec(char c) {
    if ('0' <= c && c <= '9') {
        return c - '0';
    } else if ('a' <= c && c <= 'f') {
        return c - 'a' + 10;
    } else if ('A' <= c && c <= 'F') {
        return c - 'A' + 10;
    } else {
        return -1;
    }
}

char dec2hex(short int c) {
    if (0 <= c && c <= 9) {
        return c + '0';
    } else if (10 <= c && c <= 15) {
        return c + 'A' - 10;
    } else {
        return -1;
    }
}

// 解码url
void urldecode(char url[]) {
    int i = 0;
    int len = strlen(url);
    int res_len = 0;
    char res[BURSIZE];
    for (i = 0; i < len; ++i) {
        char c = url[i];
        if (c != '%') {
            res[res_len++] = c;
        } else {
            char c1 = url[++i];
            char c0 = url[++i];
            int num = 0;
            num = hex2dec(c1) * 16 + hex2dec(c0);
            res[res_len++] = num;
        }
    }
    res[res_len] = '\0';
    strcpy(url, res);
}

int http_request_from_env(http_request_t *request) {
    char *p;

    p = getenv("HTTP_ACCEPT");
    if (NULL != p) request->http_accept = p;

    p = getenv("REQUEST_METHOD");
    if (NULL != p) request->request_method = p;

    p = getenv("QUERY_STRING");
    if (NULL != p) {
        urldecode(p);
        request->query_string = p;
    }

    p = getenv("CONTENT_LENGTH");
    if (NULL != p) request->content_length = atoi(p);
}

int http_request_from_file(http_request_t *request, FILE *fp) {
    char buf[4096] = {};
    char *s = buf, *e = s + sizeof(buf);

    while (!feof(fp)) {
        s += fread(s, e - s, 1, fp);
    }
    request->json = cJSON_Parse(buf);
}